import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

///页面跳转工具
///封装无context的路由跳转
///使用前提：在MaterialApp中配置路由---navigatorKey: PageJumpService.instance().navigatorKey,
/*使用举例
1.一般跳转
PageJumpService.instance().goTo(PageClassName());
2.跳转传值---将当前页面的数据传递到下一个页面（通过构造方法传值）
PageJumpService.instance().goTo(PageClassName(parameter1,parameter2...));
3.回退上一个页面
PageJumpService.instance().goBack();

4.新页面回传值
Page1页面代码

Future result = PageJumpService.instance().goTo(Page2("构造方法传值到新页面"));
//接收返回的参数
result.then((res) {setState(() {
        //处理Page2返回的数据res
          _handleMessage = res;
});});

page2页面代码
PageJumpService.instance().goBack("回传值res");


5.关闭当前页面，打开新页面
PageJumpService.instance().replace(PageClassName());

 */

class PageJumpService {
  factory PageJumpService.instance() => _getInstance();

  PageJumpService._internal();

  static PageJumpService _instance;

  static PageJumpService _getInstance() {
    if (_instance == null) {
      _instance = PageJumpService._internal();
    }
    return _instance;
  }

  final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();

  ///T 是路由返回值类型
  Future<T> goTo<T>(Widget routerPage, {bool fullscreenDialog}) {
    if (fullscreenDialog != null && fullscreenDialog) {
      return navigatorKey.currentState.push(MaterialPageRoute<T>(
          fullscreenDialog: true,
          builder: (BuildContext context) => routerPage));
    }
    return navigatorKey.currentState.push(
        CupertinoPageRoute<T>(builder: (BuildContext context) => routerPage));
  }

  Future<T> replace<T>(Widget routerPage) {
    return navigatorKey.currentState.pushReplacement(
        CupertinoPageRoute<T>(builder: (BuildContext context) => routerPage));
  }

  void goBack<T>([T result]) {
    return navigatorKey.currentState.pop<T>(result);
  }
}
